package com.hello.booksale.controller;

import com.hello.booksale.entity.BookEntity;
import com.hello.booksale.service.BookService;
import com.hello.booksale.service.QiniuService;
import com.hello.booksale.util.RemoteImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
@Slf4j
@Controller
public class TestController {
    @Resource
    private QiniuService qiniuService;
    @Resource
    private BookService bookService;



    @ResponseBody
    @PostMapping("/test")
    public String test(@RequestParam(name = "book-img-local") MultipartFile file, HttpServletRequest request) throws IOException {
        String isLocalImage=request.getParameter("is-local-image");
        String bookUrl="";
        if(Objects.equals(isLocalImage, "option2"))
        {
            bookUrl=qiniuService.uploadFile(file.getInputStream());

        }else if(Objects.equals(isLocalImage, "option1"))
        {
            String img=request.getParameter("book-img-url");
            if(img!=null)
            {
                InputStream inputStream=RemoteImageUtil.getImageStream(img);
                if(inputStream!=null)
                {
                    bookUrl=qiniuService.uploadFile(inputStream);
                }else{
                    log.error("远程图片加载失败");
                }
            }else{
                log.error("获取图片url失败");
            }

        }else{
            return "请选择书籍图片进行提交";
        }
        String bookAuthor=request.getParameter("book-author");
        String bookName=request.getParameter("book-name");
        Double bookPrice=Double.parseDouble(request.getParameter("book-price"));
        String bookDetail=request.getParameter("book-detail");
        int bookStock=Integer.parseInt(request.getParameter("book-stock"));
        BookEntity book=new BookEntity(bookName,bookPrice,bookDetail,bookAuthor,0,bookStock,bookUrl);
        log.info("图书信息为: {}",book);
        bookService.insertBook(book);
        return "hello";
    }

    @GetMapping("/test")
    public String test() {
        return "/book_add";
    }

}
